package com.example.petshop.controller;

import com.example.petshop.entity.Goods;
import com.example.petshop.entity.Order;
import com.example.petshop.entity.Shop;
import com.example.petshop.entity.User;
import com.example.petshop.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {
  @Autowired
  private OrderService orderService;

@GetMapping("/getAll")
public List<Order> getAll(){
  return orderService.getAll();
}
  @PostMapping("/create")
  public List<Order> createOrder(@RequestBody List<Order> orders) {
    try {
      // 保存订单并获取 ID
      for (Order order : orders) {
        order.setOrderState("0"); // 设置订单状态为 0
        orderService.saveOrder(order); // 保存订单到数据库
        System.out.println("Saved Order ID: " + order.getOrderId());
      }

      // 重新查询数据库获取订单 ID（假设有适当的方法）
      List<Order> savedOrders = orderService.getOrdersByIds(
              orders.stream().map(Order::getOrderId).collect(Collectors.toList())
      );
        System.out.println("saveOrders: "+savedOrders);
      return savedOrders; // 返回包含生成的 orderId 的订单数据
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException("Failed to create orders");
    }
  }
  @PostMapping("/updateOrderState1")
  public ResponseEntity<?> updateOrderState(@RequestBody List<Integer> orderIds) {
    System.out.println("=====================updateOrderState1============================");
    System.out.println("OrderController OrderIds: " + orderIds);
    try {
      List<Order> orders = orderService.getOrdersByIds(orderIds);
      for (Order order : orders) {
        System.out.println("Received Order ID: " + order.getOrderId() + ", Order Count: " + order.getOrderCount());
      }

      orderService.updateOrderState(orderIds, "1"); // 将订单状态更新为 "1"
      orderService.updateGoodsInventoryAndSales(orderIds); // 更新库存和销量

      return new ResponseEntity<>(HttpStatus.OK);
    } catch (Exception e) {
      e.printStackTrace(); // 输出异常堆栈信息
      return new ResponseEntity<>("更新订单状态失败：" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @PostMapping("/updateOrderStateWeb")
  public ResponseEntity<?> updateOrderStateWeb(@RequestBody Order order) {
    orderService.updateOrder(order);
    return ResponseEntity.ok().build();
  }
//  @GetMapping("/state/0")
//  public ResponseEntity<List<Order>> getGoodsByState0(){
//    List<Order> orders = orderService.getByState("0");
//    if (orders.isEmpty()) {
//      return ResponseEntity.notFound().build();
//    } else {
//      return ResponseEntity.ok(orders);
//    }
//  }
@GetMapping("/state/0")
public ResponseEntity<List<Order>> getGoodsByState0(HttpSession session) {
  // 从会话中获取登录用户的信息
  User loggedInUser = (User) session.getAttribute("loggedInUser");
System.out.println("进入getGoodsByState0中！！！");
  if (loggedInUser == null || loggedInUser.getUserId() == null) {
    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
  }

  // 获取用户ID
  Long userId = loggedInUser.getUserId();
  System.out.println("Fetching orders for userId: " + userId);

  // 根据用户ID和状态为0获取订单
  List<Order> orders = orderService.getByUserIdAndState(userId, "0");

  if (orders.isEmpty()) {
    System.out.println("No orders found for state 0 and userId: " + userId);
    return ResponseEntity.notFound().build();
  } else {
    return ResponseEntity.ok(orders);
  }
}

  @GetMapping("/state/1")
  public ResponseEntity<List<Order>> getGoodsByState1(HttpSession session) {
    // 从会话中获取登录用户的信息
    User loggedInUser = (User) session.getAttribute("loggedInUser");
    System.out.println("进入getGoodsByState0中！！！");
    if (loggedInUser == null || loggedInUser.getUserId() == null) {
      return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    // 获取用户ID
    Long userId = loggedInUser.getUserId();
    System.out.println("Fetching orders for userId: " + userId);

    // 根据用户ID和状态为0获取订单
    List<Order> orders = orderService.getByUserIdAndState(userId, "1");

    if (orders.isEmpty()) {
      System.out.println("No orders found for state 1 and userId: " + userId);
      return ResponseEntity.notFound().build();
    } else {
      return ResponseEntity.ok(orders);
    }
  }
  @GetMapping("/state/2")
  public ResponseEntity<List<Order>> getGoodsByState2(HttpSession session) {
    // 从会话中获取登录用户的信息
    User loggedInUser = (User) session.getAttribute("loggedInUser");
    System.out.println("进入getGoodsByState2中！！！");
    if (loggedInUser == null || loggedInUser.getUserId() == null) {
      return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    // 获取用户ID
    Long userId = loggedInUser.getUserId();
    System.out.println("Fetching orders for userId: " + userId);

    // 根据用户ID和状态为0获取订单
    List<Order> orders = orderService.getByUserIdAndState(userId, "2");

    if (orders.isEmpty()) {
      System.out.println("No orders found for state 2 and userId: " + userId);
      return ResponseEntity.notFound().build();
    } else {
      return ResponseEntity.ok(orders);
    }
  }
  @GetMapping("/state/3")
  public ResponseEntity<List<Order>> getGoodsByState3(HttpSession session) {
    // 从会话中获取登录用户的信息
    User loggedInUser = (User) session.getAttribute("loggedInUser");
    System.out.println("进入getGoodsByState3中！！！");
    if (loggedInUser == null || loggedInUser.getUserId() == null) {
      return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    // 获取用户ID
    Long userId = loggedInUser.getUserId();
    System.out.println("Fetching orders for userId: " + userId);

    // 根据用户ID和状态为0获取订单
    List<Order> orders = orderService.getByUserIdAndState(userId, "3");

    if (orders.isEmpty()) {
      System.out.println("No orders found for state 3 and userId: " + userId);
      return ResponseEntity.notFound().build();
    } else {
      return ResponseEntity.ok(orders);
    }
  }
  @PostMapping("/submitRemark")
  public ResponseEntity<?> submitRemark(@RequestBody Order order) {
  System.out.println("submitRemarkorder: "+order);
    List<Integer> orderIds = Collections.singletonList(order.getOrderId());
    try {
      orderService.updateRemark(order.getOrderId(), order.getRemark());
      orderService.updateOrderState(orderIds, "4");
      return ResponseEntity.ok().build();
    } catch (Exception e) {
      e.printStackTrace();
      return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
  @PostMapping("/submitReason")
  public ResponseEntity<?> submitReason(@RequestBody Order order) {
    System.out.println("submitRemarkorder: "+order);
    List<Integer> orderIds = Collections.singletonList(order.getOrderId());
    try {
      orderService.updateReason(order.getOrderId(), order.getReason());
      orderService.updateOrderState(orderIds, "-2");
      return ResponseEntity.ok().build();
    } catch (Exception e) {
      e.printStackTrace();
      return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
  @GetMapping("/getAfterSaleOrders")
  public ResponseEntity<List<Order>> getAfterSaleOrders(HttpSession session) {
    // 从会话中获取登录用户的信息
    User loggedInUser = (User) session.getAttribute("loggedInUser");
    if (loggedInUser == null || loggedInUser.getUserId() == null) {
      return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    // 获取用户ID
    Long userId = loggedInUser.getUserId();

    // 获取订单状态为-1、-2、-3的订单
    List<Order> orders = orderService.getAfterOrdersByUserIdAndStates(userId, Arrays.asList("-1", "-2", "-3"));

    if (orders.isEmpty()) {
      return ResponseEntity.notFound().build();
    } else {
      return ResponseEntity.ok(orders);
    }
  }

  @GetMapping("/remarks")
  public ResponseEntity<List<Order>> getRemarksByGoodsName(@RequestParam String goodsName) {
    try {
      List<Order> remarks = orderService.getRemarksByGoodsName(goodsName);
      if (remarks.isEmpty()) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
      } else {
        return new ResponseEntity<>(remarks, HttpStatus.OK);
      }
    } catch (Exception e) {
      e.printStackTrace();
      return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
  @GetMapping("/getByShopId")
  public ResponseEntity<List<Order>> getOrdersByShopId(@RequestParam int shopId) {
    List<Order> orders = orderService.getByShopId(shopId);
    if (orders.isEmpty()) {
      return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } else {
      return new ResponseEntity<>(orders, HttpStatus.OK);
    }
  }

}


